package com.wechar_rpa.controller;

import com.wechar_rpa.service.SubscriptionService;
import com.wechar_rpa.service.WeChatPayService;
import com.wechatpay.java.service.payment.model.UnifiedOrderResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wechatpay")
public class WeChatPayController {

    @Autowired
    private WeChatPayService weChatPayService;

    @Autowired
    private SubscriptionService subscriptionService;

    @GetMapping("/prepay")
    public Map<String, Object> createPrepayOrder(
            @RequestParam String userId,
            @RequestParam int planLevel) {
        UnifiedOrderResponse response = weChatPayService.createPrepayOrder(userId, planLevel);
        if (response == null) return new HashMap<>();

        // 返回前端需要的支付参数
        Map<String, Object> result = new HashMap<>();
        result.put("timestamp", System.currentTimeMillis() / 1000);
        result.put("nonceStr", response.getNonceStr());
        result.put("package", "prepay_id=" + response.getPrepayId());
        result.put("signType", "RSA");
        result.put("paySign", response.getSign());
        return result;
    }

    @PostMapping("/notify")
    public String handlePaymentNotify(@RequestBody Map<String, Object> notifyData) {
        // 处理支付结果通知
        String transactionId = (String) notifyData.get("transaction_id");
        String outTradeNo = (String) notifyData.get("out_trade_no");
        String tradeState = (String) notifyData.get("trade_state");

        if ("SUCCESS".equals(tradeState)) {
            // 模拟从订单号获取用户和套餐信息
            String userId = extractUserIdFromOutTradeNo(outTradeNo);
            int planLevel = extractPlanLevelFromOutTradeNo(outTradeNo);

            // 更新用户订阅状态
            subscriptionService.subscribeUser(userId, planLevel);
            System.out.println("支付成功并已更新订阅: " + outTradeNo);
        }

        return "<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>";
    }

    private String extractUserIdFromOutTradeNo(String outTradeNo) {
        // 实际应从数据库或缓存中查找
        return "test_user";
    }

    private int extractPlanLevelFromOutTradeNo(String outTradeNo) {
        // 示例：根据订单号解析等级（实际应从数据库查）
        return 2;
    }
}